<template>
    <div class="homework-container">
      <!-- 左边的表格 -->
      <div class="table-container" style="width: 60%; margin-right: 20px;">
        <!-- 筛选器区域 -->
        <div class="filters" style="display: flex; justify-content: space-between; margin-bottom: 20px;">
          <div style="display: flex; align-items: center;">
            <label for="subject-select" style="margin-right: 8px;">科目名称：</label>
            <el-select v-model="selectedSubject" placeholder="请选择科目" @change="filterHomeworkList">
              <el-option label="全部" value="" key="all-subjects"></el-option>
              <el-option
                v-for="subject in uniqueSubjects"
                :key="subject"
                :label="subject"
                :value="subject"
              ></el-option>
            </el-select>
          </div>
          <div style="display: flex; align-items: center;">
            <label for="status-select" style="margin-right: 8px;">状态：</label>
            <el-select v-model="selectedStatus" placeholder="请选择状态" @change="filterHomeworkList">
              <el-option label="全部" value="" key="all-statuses"></el-option>
              <el-option
                v-for="status in uniqueStatuses"
                :key="status"
                :label="status"
                :value="status"
              ></el-option>
            </el-select>
          </div>
        </div>
  
        <!-- 表格 -->
        <el-table
          highlight-current-row
          :data="filteredHomeworkList"
          style="width: 100%;"
          @row-click="handleRowClick"
          row-class-name="homework-row"
          header-row-class-name="homework-header"
          max-height="650"
        >
          <el-table-column prop="expId" label="作业标识" width="70" align="center"></el-table-column>
          <el-table-column prop="homeworkId" label="作业ID" width="130" align="center"></el-table-column>
          <el-table-column prop="subjectName" label="科目名称" width="120" align="center"></el-table-column>
          <el-table-column prop="subDate" label="发布日期" width="160" align="center"></el-table-column>
          <el-table-column prop="status" label="状态" width="150" align="center"></el-table-column>
          <el-table-column prop="grade" label="成绩" width="100" align="center"></el-table-column>
        </el-table>
      </div>
  
      <!-- 右边的详情区域 -->
      <div class="homework-details" v-if="selectedHomework" style="width: 40%;">
        <div class="details-header">
          <h3 class="details-title">作业详情</h3>
        </div>
        <div class="details-content">
          <div class="details-item">
            <div class="label">作业标识：</div>
            <div class="value">{{ selectedHomework.expId }}</div>
          </div>
          <div class="details-item">
            <div class="label">作业ID：</div>
            <div class="value">{{ selectedHomework.homeworkId }}</div>
          </div>
          <div class="details-item">
            <div class="label">科目名称：</div>
            <div class="value">{{ selectedHomework.subjectName }}</div>
          </div>
          <div class="details-item">
            <div class="label">教师：</div>
            <div class="value">{{ selectedHomework.username }}</div>
          </div>
          <div class="details-item">
            <div class="label">发布日期：</div>
            <div class="value">{{ selectedHomework.subDate }}</div>
          </div>
          <div class="details-item">
            <div class="label">状态：</div>
            <div class="value">{{ selectedHomework.status }}</div>
          </div>
          <div class="details-item">
            <div class="label">成绩：</div>
            <div class="value">{{ selectedHomework.grade }}</div>
          </div>
          <div class="details-item">
            <div class="label">评语：</div>
            <div class="value">{{ selectedHomework.comments }}</div>
          </div>
          <div class="details-item">
            <div class="label">作业内容：</div>
            <div class="value">{{ selectedHomework.remark }}</div>
          </div>
          <div class="details-item">
            <div class="label">截止日期：</div>
            <div class="value">{{ selectedHomework.endline }}</div>
          </div>
          <div class="details-item">
            <div class="label">题目附件：</div>
            <a href="" @click.prevent="downFile(selectedHomework.filePath)">{{ selectedHomework.filePath }}</a>
          </div>
          <div class="details-item">
            <div class="label">答案附件：</div>
            <div v-if="selectedHomework.fileCompletePath">
              <a href="" @click.prevent="downFile(selectedHomework.fileCompletePath)">
                {{ selectedHomework.fileCompletePath }}
              </a>
              <button @click="clearFile">删除文件</button>
            </div>
            <div v-else>
              <input class="el-select" ref="fileInput" type="file" @change="handleFileChange" />
            </div>
          </div>
        </div>
        <div class="submit-button">
          <el-button type="primary" @click="confirmSubmit">提交作业</el-button>
        </div>
      </div>
      <h1 v-else style="width: 40%;">选择展示作业详情</h1>
    </div>
  </template>
  
  <script>
  import '@/utils/InterceptorUtils';
  import { getFile, getHomeworks, putFile } from '@/utils/urlManager';
  import axios from 'axios';
  
  export default {
    data() {
      return {
        homeworkList: [], // 作业列表
        filteredHomeworkList: [], // 筛选后的作业列表
        selectedHomework: null, // 当前选中的作业详情
        file: null, // 当前选择的文件
        selectedSubject: '', // 选中的科目名称
        selectedStatus: '', // 选中的状态
      };
    },
    computed: {
      // 获取所有唯一的科目名称
      uniqueSubjects() {
        return [...new Set(this.homeworkList.map(item => item.subjectName))];
      },
      // 获取所有唯一的状态
      uniqueStatuses() {
        return [...new Set(this.homeworkList.map(item => item.status))];
      },
    },
    mounted() {
      this.fetchHomeworkList();
    },
    methods: {
      handleFileChange(event) {
        this.file = event.target.files[0];
        this.selectedHomework.fileCompletePath = this.file.name; // 显示文件名
      },
      clearFile() {
        this.file = null; // 清除文件
        this.selectedHomework.fileCompletePath = null; // 清除文件名
        this.$refs.fileInput.value = ''; // 清除文件输入框的值
      },
      // 下载文件
      downFile(filename) {
        axios.get(getFile + filename, { responseType: 'blob' })
          .then((response) => {
            const link = document.createElement('a');
            link.style.display = 'none';
            link.href = URL.createObjectURL(response.data);
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(link.href);
          })
          .catch((error) => {
            console.error('下载失败:', error);
            this.$message.error('文件下载失败，请稍后再试');
          });
      },
      // 获取作业列表
      fetchHomeworkList() {
        axios.get(getHomeworks)
          .then(response => {
            if (response.data.data) {
              this.homeworkList = response.data.data;
              console.log(this.homeworkList);
              
              this.filteredHomeworkList = this.homeworkList; // 初始化筛选列表
            } else {
              this.$message.warning("获取作业信息失败");
            }
          })
          .catch(error => {
            console.error(error);
            this.$message.error("网络请求失败，请稍后重试");
          });
      },
      // 表格行点击事件
      handleRowClick(row) {
        this.selectedHomework = row;
      },
      // 筛选作业列表
      filterHomeworkList() {
        this.filteredHomeworkList = this.homeworkList.filter(item => {
          return (
            (!this.selectedSubject || item.subjectName === this.selectedSubject) &&
            (!this.selectedStatus || item.status === this.selectedStatus)
          );
        });
      },
      // 提交作业
      confirmSubmit() {
        if (!this.selectedHomework) {
          this.$message.warning("请先选择一个作业");
          return;
        }
        this.$confirm('确认提交吗?', '提交确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.submitHomework();
        }).catch((err) => {
          console.error(err)
          this.$message.info('提交已取消');
        });
      },
      // 处理提交逻辑
      submitHomework() {
        if (!this.file) {
          this.$message.error("请先选择一个文件");
          return;
        }
        const formData = new FormData();
        formData.append('file', this.file);
        formData.append('homeworkId', this.selectedHomework.homeworkId);
        formData.append('expId', this.selectedHomework.expId);
  
        axios.post(putFile, formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
          .then(response => {
            if (response.data.data != null) {
              console.log(response.data);
              this.$message.success("作业上传成功");
              this.fetchHomeworkList();
            } else {
              this.$message.warning(response.data.msg);
            }
          })
          .catch(error => {
            console.log(error);
            this.$message.error("出错啦~~~");
          });
      }
    }
  };
  </script>
  
  <style scoped>
  .homework-container {
    display: flex;
    height: 100%;
    width: 100%;
    background-color: #f5f5f5;
    padding: 20px;
    box-sizing: border-box;
  }
  
  .table-container {
    width: 50%;
    margin-right: 20px;
  }
  
  .homework-details {
    width: 40%;
    padding: 20px;
    box-sizing: border-box;
    background-color: #ffffff;
    border-radius: 8px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
    overflow: auto;
  }
  
  .details-header {
    background-color: #f0f0f0;
    padding: 10px 0;
    border-bottom: 1px solid #e0e0e0;
    text-align: center;
  }
  
  .details-title {
    font-size: 18px;
    font-weight: bold;
    color: #333333;
  }
  
  .details-content {
    padding-top: 10px;
  }
  
  .details-item {
    display: grid;
    grid-template-columns: 120px 1fr;
    gap: 8px;
    align-items: center;
    margin-bottom: 10px;
  }
  
  .label {
    font-weight: bold;
    white-space: nowrap;
    background-color: #f0f0f0;
    padding: 5px 10px;
    border-radius: 4px;
  }
  
  .value {
    background-color: #f9f9f9;
    padding: 5px 10px;
    border-radius: 4px;
    box-sizing: border-box;
  }
  
  .submit-button {
    text-align: center;
    margin-top: 20px;
  }
  </style>